#pragma once
#include "Util.hpp"
#include<unordered_map>
namespace shw
{
#define SEP_1 "  "
#define SEP_2 "\n"
#define BACK_FILE "./cilent.dat"
class Datamanger
{
private:
	std::string _back_file;
	std::unordered_map<std::string,std::string> _table;
public:
		Datamanger(const std::string& back_file=BACK_FILE):_back_file(back_file)
		{
			InLoad();
		}
		void Split(const std::string& body, const std::string& SEP, std::vector<std::string>& arr)
		{
			size_t begin = 0;
			while (begin < body.size())
			{
				size_t pos = body.find(SEP.c_str(), begin);
				if (pos == std::string::npos)
				{
					break;
				}
				arr.push_back(std::string(body.substr(begin, pos - begin)));
				begin = pos + SEP.size();
			}
			if (begin < body.size()) { arr.push_back(std::string(body.substr(begin))); }

		}
		void InLoad()
		{
			icloud::FileUtil fut(_back_file);
			if (fut.Exists())
			{
				std::string body;
				fut.GetContent(body);
				std::vector<std::string> arr;
				Split(body, SEP_2, arr);
				for (auto& it : arr)
				{
					std::vector<std::string> tmp;
					Split(it, SEP_1, tmp);
					_table[tmp[0]] = tmp[1];
				}
			}
		}
		bool Storage()
		{
			std::stringstream ss;
			auto it = _table.begin();
			while (it != _table.end())
			{
				ss << it->first << SEP_1 << it->second << SEP_2;
				++it;
			}
			std::string body = ss.str();
			icloud::FileUtil fut(_back_file);
			return fut.WriteContet(body);
		}
		bool Insert(const std::string& key,const std::string& value)
		{
			_table[key] = value;
			Storage();
			return true;

		}
		bool GetByKey(const std::string& key,std::string& value)
		{
			auto it = _table.find(key);
			if (it == _table.end())
			{
				return false;
			}
			value = it->second;
			return true;
		}
		bool UpData(const std::string& key, const std::string& value)//����������Ϣ
		{
			_table[key] = value;
			return Storage();
		}
	};
}